<template>
	<view class="login-container">
		<!-- 登录卡片 -->
		<view class="login-card">
			<!-- 头部区域 -->
			<view class="login-header">
				<text class="app-name">会议室预约系统</text>
				<text class="app-subtitle">Meeting Room Booking</text>
			</view>
			
			<!-- 登录表单 -->
			<view class="login-form">
				<view class="input-group">
					<input 
						class="input-field" 
						type="text" 
						v-model="username" 
						placeholder="请输入用户名"
						placeholder-class="input-placeholder"
					/>
					
					<input 
						class="input-field" 
						type="password" 
						v-model="password" 
						placeholder="请输入密码"
						placeholder-class="input-placeholder"
					/>
					
					<!-- 验证码输入区域 -->
					<view class="captcha-group">
						<input 
							class="captcha-input" 
							type="text" 
							v-model="captchaCode" 
							placeholder="请输入验证码"
							placeholder-class="input-placeholder"
							maxlength="4"
						/>
						<view class="captcha-image" @click="refreshCaptcha">
							<image 
								v-if="codeUrl" 
								:src="codeUrl" 
								mode="aspectFit"
								class="captcha-img"
							/>
							<view v-else class="captcha-placeholder">
								<text>点击获取验证码</text>
							</view>
						</view>
					</view>
				</view>
				
				<button 
					class="login-btn" 
					:class="{ disabled: !canLogin, loading: isLoading }"
					:disabled="!canLogin"
					@click="handleLogin"
				>
					<text v-if="!isLoading">登录</text>
					<text v-else>登录中...</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
import api, { handleApiError } from '@/utils/api.js'

export default {
	data() {
		return {
			username: '',
			password: '',
			captchaCode: '',
			codeUrl: '',
			uuid: '',
			isLoading: false
		}
	},
	computed: {
		canLogin() {
			return this.username.trim() && this.password.trim() && this.captchaCode.trim() && !this.isLoading;
		}
	},
	onLoad() {
		// 检查是否已登录，如果已登录则自动跳转到首页
		const token = uni.getStorageSync('token');
		const userInfo = uni.getStorageSync('userInfo');
		
		if (token && userInfo) {
			// 如果已登录，直接跳转到首页，不加载验证码
			uni.reLaunch({
				url: '/pages/index/index'
			});
		} else {
			// 如果未登录，加载验证码
			this.refreshCaptcha();
		}
	},
	mounted() {
		// mounted 钩子中不需要再次检查，onLoad 已经处理了
		// 如果 onLoad 中已登录，页面会直接跳转，不会执行到这里
	},
	methods: {
		// 获取验证码
		async refreshCaptcha() {
			try {
				const response = await api.getCaptcha()
				if (response && response.code === 200) {
					this.codeUrl = "data:image/gif;base64," + response.img
					this.uuid = response.uuid
				} else {
					uni.showToast({
						title: '获取验证码失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('获取验证码错误:', error)
				uni.showToast({
					title: '获取验证码失败',
					icon: 'none'
				})
			}
		},
		
		async handleLogin() {
			if (!this.canLogin) {
				uni.showToast({
					title: '请填写完整信息',
					icon: 'none'
				});
				return;
			}
			
			this.isLoading = true;
			uni.showLoading({
				title: '登录中...'
			});
			
			try {
				// 调用后端登录接口
				const response = await api.login(this.username, this.password, this.captchaCode, this.uuid);
				
				uni.hideLoading();
				this.isLoading = false;
				
				// 检查登录响应
				if (response && response.code === 200) {
					// 保存token
					uni.setStorageSync('token', response.token);
					
					// 获取完整的用户信息
					try {
						const userInfoResponse = await api.getUserInfo();
						if (userInfoResponse && userInfoResponse.code === 200) {
							const user = userInfoResponse.user;
							// 保存完整的用户信息到本地存储
							const userInfo = {
								userId: user.userId,
								userName: user.userName,
								nickName: user.nickName,
								nickname: user.nickName,
								deptName: user.dept?.deptName || '未知部门',
								department: user.dept?.deptId || '未知部门',
								email: user.email || '',
								phone: user.phonenumber || '',
								phonenumber: user.phonenumber || '',
								avatar: user.avatar || '',
								roles: userInfoResponse.roles || [],
								permissions: userInfoResponse.permissions || []
							};
							uni.setStorageSync('userInfo', userInfo);
						} else {
							// 如果获取用户信息失败，使用基本信息
							uni.setStorageSync('userInfo', {
								username: this.username,
								userName: this.username,
								nickname: this.username,
								nickName: this.username,
								department: '未知部门',
								deptName: '未知部门',
								userId: this.username
							});
						}
					} catch (error) {
						console.error('获取用户信息错误:', error);
						// 如果获取用户信息失败，使用基本信息
						uni.setStorageSync('userInfo', {
							username: this.username,
							userName: this.username,
							nickname: this.username,
							nickName: this.username,
							department: '未知部门',
							deptName: '未知部门',
							userId: this.username
						});
					}
					
					uni.showToast({
						title: '登录成功',
						icon: 'success',
						duration: 1500
					});
					
					// 跳转到首页
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}, 1500);
				} else {
					// 登录失败
					uni.showToast({
						title: response.msg || '登录失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				this.isLoading = false;
				
				// 使用统一的错误处理
				handleApiError(error);
			}
		}
	}
}
</script>

<style lang="less" scoped>
page {
	background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-container {
	min-height: 100vh;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 40rpx;
}

/* 登录卡片 */
.login-card {
	width: 100%;
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 60rpx 40rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

/* 头部区域 */
.login-header {
	text-align: center;
	margin-bottom: 60rpx;
}

.app-name {
	font-size: 48rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 10rpx;
}

.app-subtitle {
	font-size: 24rpx;
	color: #666;
	opacity: 0.8;
}

/* 登录表单 */
.login-form {
	width: 100%;
}

.input-group {
	display: flex;
	flex-direction: column;
	gap: 30rpx;
	margin-bottom: 50rpx;
}

/* 验证码输入区域 */
.captcha-group {
	display: flex;
	gap: 20rpx;
	align-items: center;
}

.captcha-input {
	flex: 1;
	height: 90rpx;
	background: #f8f9fa;
	border: 2rpx solid #e9ecef;
	border-radius: 12rpx;
	padding: 0 20rpx;
	font-size: 30rpx;
	color: #333;
	box-sizing: border-box;
}

.captcha-input:focus {
	border-color: #2870E5;
	background: #fff;
}

.captcha-image {
	width: 200rpx;
	height: 90rpx;
	background: #f8f9fa;
	border: 2rpx solid #e9ecef;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.3s ease;
}

.captcha-image:active {
	background: #e9ecef;
	transform: scale(0.98);
}

.captcha-img {
	width: 100%;
	height: 100%;
	border-radius: 10rpx;
}

.captcha-placeholder {
	text-align: center;
	color: #999;
	font-size: 24rpx;
}

.input-field {
	width: 100%;
	height: 90rpx;
	background: #f8f9fa;
	border: 2rpx solid #e9ecef;
	border-radius: 12rpx;
	padding: 0 20rpx;
	font-size: 30rpx;
	color: #333;
	box-sizing: border-box;
}

.input-field:focus {
	border-color: #2870E5;
	background: #fff;
}

.input-placeholder {
	color: #999;
	font-size: 28rpx;
}

/* 登录按钮 */
.login-btn {
	width: 100%;
	height: 90rpx;
	line-height: 90rpx;
	background: #2870E5;
	color: #fff;
	border: none;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: bold;
	transition: all 0.3s ease;
}

.login-btn:active {
	background: #1e5bb8;
	transform: scale(0.98);
}

.login-btn.disabled {
	background: #e9ecef;
	color: #999;
}

.login-btn.disabled:active {
	transform: none;
}

.login-btn.loading {
	background: #94a3b8;
	cursor: not-allowed;
}

.login-btn.loading:active {
	transform: none;
}
</style>